"""
云盘SDK客户端

提供统一的云盘操作接口。
"""

import os
import json
from typing import Dict, Any, List, Optional, Union
from .base import BaseCloudProvider, CloudFile, UploadResult, DownloadResult
from .models import CloudSDKConfig, ProviderConfig
from .storage import StorageManager, ConfigManager, SessionManager
from .factory import CloudProviderFactory


class CloudSDK:
    """云盘SDK客户端"""
    
    def __init__(self, config_path: Optional[str] = None):
        """
        初始化SDK
        
        Args:
            config_path: 配置文件路径
        """
        self.providers: Dict[str, BaseCloudProvider] = {}
        
        # 初始化存储管理器
        if config_path:
            base_path = os.path.dirname(config_path)
        else:
            base_path = os.path.join(os.path.expanduser("~"), ".cloud_sdk")
        
        self.storage_manager = StorageManager(base_path)
        self.config_manager = ConfigManager(self.storage_manager)
        self.session_manager = SessionManager(self.storage_manager)
        
        # 初始化工厂
        self.factory = CloudProviderFactory()
        
        # 加载配置并初始化提供者
        self._load_providers()
    
    def _load_providers(self) -> None:
        """加载配置中的提供者"""
        config = self.config_manager.config
        for provider_config in config.providers:
            if provider_config.enabled:
                try:
                    provider = CloudProviderFactory.create_provider(
                        provider_config.type, 
                        provider_config.config
                    )
                    if provider:
                        self.providers[provider_config.type] = provider
                except Exception as e:
                    print(f"加载提供者 {provider_config.type} 失败: {e}")
    
    def add_provider(self, provider_type: str, config: Dict[str, Any], 
                    name: Optional[str] = None) -> BaseCloudProvider:
        """
        添加云盘提供者
        
        Args:
            provider_type: 提供者类型
            config: 配置参数
            name: 提供者名称
            
        Returns:
            BaseCloudProvider: 提供者实例
        """
        if name is None:
            name = provider_type
        
        # 创建提供者配置
        provider_config = ProviderConfig(
            type=provider_type,
            name=name,
            enabled=True,
            config=config
        )
        
        # 保存配置
        self.config_manager.add_provider(provider_config)
        
        # 创建提供者实例
        provider = CloudProviderFactory.create_provider(provider_type, config)
        if provider:
            self.providers[provider_type] = provider
        
        return provider
    
    def get_provider(self, provider_type: str) -> Optional[BaseCloudProvider]:
        """
        获取提供者实例
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            Optional[BaseCloudProvider]: 提供者实例，不存在返回None
        """
        return self.providers.get(provider_type)
    
    def remove_provider(self, provider_type: str) -> bool:
        """
        移除提供者
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否移除成功
        """
        # 从内存中移除
        if provider_type in self.providers:
            del self.providers[provider_type]
        
        # 从配置中移除
        success = self.config_manager.remove_provider(provider_type)
        
        # 删除会话
        self.session_manager.delete_session(provider_type)
        
        return success
    
    def list_providers(self) -> List[str]:
        """
        列出所有提供者类型
        
        Returns:
            List[str]: 提供者类型列表
        """
        return list(self.providers.keys())
    
    def login_all(self) -> Dict[str, bool]:
        """
        登录所有提供者
        
        Returns:
            Dict[str, bool]: 登录结果
        """
        results = {}
        for provider_type, provider in self.providers.items():
            try:
                results[provider_type] = provider.login()
            except Exception as e:
                print(f"登录 {provider_type} 失败: {e}")
                results[provider_type] = False
        return results
    
    def logout_all(self) -> Dict[str, bool]:
        """
        登出所有提供者
        
        Returns:
            Dict[str, bool]: 登出结果
        """
        results = {}
        for provider_type, provider in self.providers.items():
            try:
                results[provider_type] = provider.logout()
            except Exception as e:
                print(f"登出 {provider_type} 失败: {e}")
                results[provider_type] = False
        return results
    
    def save_all_sessions(self, directory: str = None) -> Dict[str, bool]:
        """
        保存所有会话
        
        Args:
            directory: 保存目录
            
        Returns:
            Dict[str, bool]: 保存结果
        """
        results = {}
        for provider_type, provider in self.providers.items():
            try:
                if hasattr(provider, '_session_data'):
                    success = self.session_manager.save_session(
                        provider_type, 
                        provider._session_data
                    )
                    results[provider_type] = success
                else:
                    results[provider_type] = False
            except Exception as e:
                print(f"保存 {provider_type} 会话失败: {e}")
                results[provider_type] = False
        return results
    
    def load_all_sessions(self, directory: str = None) -> Dict[str, bool]:
        """
        加载所有会话
        
        Args:
            directory: 会话目录
            
        Returns:
            Dict[str, bool]: 加载结果
        """
        results = {}
        for provider_type, provider in self.providers.items():
            try:
                session_data = self.session_manager.load_session(provider_type)
                if session_data and hasattr(provider, '_session_data'):
                    provider._session_data = session_data
                    results[provider_type] = True
                else:
                    results[provider_type] = False
            except Exception as e:
                print(f"加载 {provider_type} 会话失败: {e}")
                results[provider_type] = False
        return results